/**
 *  EKology - An Ecosystem Simulation Framework
 *  Copyright (C) 2008  Aarón Tavío - aaron.tavio at gmail.com - ULPGC
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package net.ekology.core.gui;

import net.ekology.*;
import net.ekology.core.Fecade;
import net.ekology.core.gui.*;
import net.ekology.core.gui.tasks.*;
import net.ekology.core.datatypes.*;
import net.ekology.core.gui.datatypes.*;
import net.ekology.ekosystem.*;
import net.ekology.ekosystem.datatypes.*;
import net.ekology.core.gui.Project;

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import org.jdesktop.application.Task;

import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.Point;
import java.awt.Cursor;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.*;
import java.util.Vector;
import java.util.Arrays;


/**
 * @author Aarón Tavío - aaron.tavio at gmail.com
 * @version 1.0.0 - 20081019-1700
 */
public class EKologyView extends FrameView {

    public EKologyView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });

        jfcDirectoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        jfcFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        
        oFecade = Fecade.getInstance();
        oViewport = (EKologyViewport) oViewportPanel; // oViewportPanel is actually an EKologyViewport object but NetBeans only allows me to declare it as a JPanel
        oEKTree = (EKosystemTree) oTree;
        oFecade.setViewport(oViewport);
        oObjectPaneFactory = new ObjectPaneFactory(this, jspObjectPane);
        
        reset();
    }

    @Action
    public void showAboutBox() {
        if (jdAboutBox == null) {
            jdAboutBox = new EKologyAboutBox(jfMainFrame);
            jdAboutBox.setLocationRelativeTo(jfMainFrame);
        }
        EKology.getApplication().show(jdAboutBox);
    }

    @Action(block = Task.BlockingScope.APPLICATION)
    public Task loadModel() {
        File oDirectory;
        Task oTask = null;

        oDirectory = showOpenDirectoryDialog();

        if (oDirectory != null) {
            oTask = new ModelLoadTask(EKology.getApplication(), this, oDirectory);
            statusMessageLabel.setText(oTask.getMessage());
            
            jtbPlay.setEnabled(true);
            jStepSimulationButton.setEnabled(true);
            jmiSaveProject.getAction().setEnabled(true);
        } else {
            statusMessageLabel.setText("Cancelled!");
        }

        return oTask;
    }

    public File showOpenDirectoryDialog() {
        int iResult;
        
        iResult = jfcDirectoryChooser.showOpenDialog(jfMainFrame);
        return (iResult == JFileChooser.APPROVE_OPTION) ? jfcDirectoryChooser.getSelectedFile() : null;
    }
    
    public File showOpenFileDialog() {
        int iResult;

        iResult = jfcFileChooser.showOpenDialog(jfMainFrame);
        return (iResult == JFileChooser.APPROVE_OPTION) ? jfcFileChooser.getSelectedFile() : null;
    }
    
    public File showSaveFileDialog() {
        int iResult;

        iResult = jfcFileChooser.showSaveDialog(jfMainFrame);
        return (iResult == JFileChooser.APPROVE_OPTION) ? jfcFileChooser.getSelectedFile() : null;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpMain = new javax.swing.JPanel();
        jtbMain = new javax.swing.JToolBar();
        jtbPlay = new javax.swing.JToggleButton();
        jStepSimulationButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jResetViewportButton = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        timeFactorLabel = new javax.swing.JLabel();
        timeFactorSpinner = new javax.swing.JSpinner();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        drawingButton = new javax.swing.JToggleButton();
        jMainSplitPane = new javax.swing.JSplitPane();
        jSplitControlPane = new javax.swing.JSplitPane();
        jspEKosystemTree = new javax.swing.JScrollPane();
        oTree = new EKosystemTree();
        jspObjectPane = new javax.swing.JScrollPane();
        oViewportPanel = new net.ekology.core.gui.EKologyViewport();
        oViewportPanel.setCursor(oViewportCursor);
        jmbMenu = new javax.swing.JMenuBar();
        javax.swing.JMenu jmFile = new javax.swing.JMenu();
        jmiLoadModel = new javax.swing.JMenuItem();
        jmiSaveProject = new javax.swing.JMenuItem();
        jmiLoadProject = new javax.swing.JMenuItem();
        javax.swing.JMenuItem jmiExit = new javax.swing.JMenuItem();
        jmProject = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        javax.swing.JMenu jmHelp = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        jpStatus = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        jpMain.setName("jpMain"); // NOI18N

        jtbMain.setFloatable(false);
        jtbMain.setRollover(true);
        jtbMain.setName("jtbMain"); // NOI18N
        jtbMain.setPreferredSize(new java.awt.Dimension(456, 33));

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(net.ekology.EKology.class).getContext().getResourceMap(EKologyView.class);
        jtbPlay.setText(resourceMap.getString("playPauseButton.text")); // NOI18N
        jtbPlay.setActionCommand(resourceMap.getString("playPauseButton.actionCommand")); // NOI18N
        jtbPlay.setEnabled(false);
        jtbPlay.setFocusable(false);
        jtbPlay.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jtbPlay.setName("playPauseButton"); // NOI18N
        jtbPlay.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jtbPlay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtbPlayActionPerformed(evt);
            }
        });
        jtbMain.add(jtbPlay);
        jtbPlay.getAccessibleContext().setAccessibleName(resourceMap.getString("playButton.AccessibleContext.accessibleName")); // NOI18N

        jStepSimulationButton.setText(resourceMap.getString("stepButton.text")); // NOI18N
        jStepSimulationButton.setActionCommand(resourceMap.getString("stepButton.actionCommand")); // NOI18N
        jStepSimulationButton.setEnabled(false);
        jStepSimulationButton.setFocusable(false);
        jStepSimulationButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jStepSimulationButton.setName("stepButton"); // NOI18N
        jStepSimulationButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jStepSimulationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jStepSimulationButtonActionPerformed(evt);
            }
        });
        jtbMain.add(jStepSimulationButton);
        jStepSimulationButton.getAccessibleContext().setAccessibleName(resourceMap.getString("jButton1.AccessibleContext.accessibleName")); // NOI18N

        jSeparator1.setName("jSeparator1"); // NOI18N
        jtbMain.add(jSeparator1);

        jResetViewportButton.setText(resourceMap.getString("jResetViewportButton.text")); // NOI18N
        jResetViewportButton.setActionCommand(resourceMap.getString("jResetViewportButton.actionCommand")); // NOI18N
        jResetViewportButton.setFocusable(false);
        jResetViewportButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jResetViewportButton.setName("jResetViewportButton"); // NOI18N
        jResetViewportButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jResetViewportButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jResetViewportButtonActionPerformed(evt);
            }
        });
        jtbMain.add(jResetViewportButton);

        jSeparator2.setName("jSeparator2"); // NOI18N
        jtbMain.add(jSeparator2);

        timeFactorLabel.setText(resourceMap.getString("timeFactorLabel.text")); // NOI18N
        timeFactorLabel.setName("timeFactorLabel"); // NOI18N
        jtbMain.add(timeFactorLabel);
        timeFactorLabel.getAccessibleContext().setAccessibleName(resourceMap.getString("timeFactorLabel.AccessibleContext.accessibleName")); // NOI18N

        timeFactorSpinner.setModel(new javax.swing.SpinnerNumberModel(1.0d, 1.0d, 15.0d, 1.0d));
        timeFactorSpinner.setName("timeFactorSpinner"); // NOI18N
        timeFactorSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                timeFactorSpinnerStateChanged(evt);
            }
        });
        jtbMain.add(timeFactorSpinner);

        jSeparator3.setName("jSeparator3"); // NOI18N
        jtbMain.add(jSeparator3);

        drawingButton.setSelected(true);
        drawingButton.setText(resourceMap.getString("drawingButton.text")); // NOI18N
        drawingButton.setFocusable(false);
        drawingButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        drawingButton.setName("drawingButton"); // NOI18N
        drawingButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        drawingButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                drawingButtonActionPerformed(evt);
            }
        });
        jtbMain.add(drawingButton);

        jMainSplitPane.setName("jMainSplitPane"); // NOI18N

        jSplitControlPane.setDividerLocation(200);
        jSplitControlPane.setDividerSize(3);
        jSplitControlPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitControlPane.setName("jSplitControlPane"); // NOI18N

        jspEKosystemTree.setName("jspEKosystemTree"); // NOI18N

        oTree.setAutoscrolls(true);
        oTree.setDragEnabled(true);
        oTree.setName("oTree"); // NOI18N
        oTree.setScrollsOnExpand(true);
        oTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                oTreeMouseClicked(evt);
            }
        });
        oTree.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                oTreePropertyChange(evt);
            }
        });
        jspEKosystemTree.setViewportView(oTree);

        jSplitControlPane.setLeftComponent(jspEKosystemTree);

        jspObjectPane.setName("jspObjectPane"); // NOI18N
        jSplitControlPane.setRightComponent(jspObjectPane);

        jMainSplitPane.setLeftComponent(jSplitControlPane);

        oViewportPanel.setBackground(resourceMap.getColor("oViewportPanel.background")); // NOI18N
        oViewportPanel.setName("oViewportPanel"); // NOI18N
        oViewportPanel.setNextFocusableComponent(jspEKosystemTree);
        oViewportPanel.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
            public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                oViewportPanelMouseWheelMoved(evt);
            }
        });
        oViewportPanel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                oViewportPanelMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                oViewportPanelMouseReleased(evt);
            }
        });
        oViewportPanel.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                oViewportPanelComponentResized(evt);
            }
        });
        oViewportPanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                oViewportPanelMouseDragged(evt);
            }
        });
        oViewportPanel.addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
            public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
            }
            public void ancestorResized(java.awt.event.HierarchyEvent evt) {
                oViewportPanelAncestorResized(evt);
            }
        });

        javax.swing.GroupLayout oViewportPanelLayout = new javax.swing.GroupLayout(oViewportPanel);
        oViewportPanel.setLayout(oViewportPanelLayout);
        oViewportPanelLayout.setHorizontalGroup(
            oViewportPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 695, Short.MAX_VALUE)
        );
        oViewportPanelLayout.setVerticalGroup(
            oViewportPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 539, Short.MAX_VALUE)
        );

        jMainSplitPane.setRightComponent(oViewportPanel);
        oViewportPanel.getAccessibleContext().setAccessibleName(resourceMap.getString("oCanvas.AccessibleContext.accessibleName")); // NOI18N
        oViewportPanel.getAccessibleContext().setAccessibleDescription(resourceMap.getString("oCanvas.AccessibleContext.accessibleDescription")); // NOI18N

        javax.swing.GroupLayout jpMainLayout = new javax.swing.GroupLayout(jpMain);
        jpMain.setLayout(jpMainLayout);
        jpMainLayout.setHorizontalGroup(
            jpMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jMainSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
            .addComponent(jtbMain, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
        );
        jpMainLayout.setVerticalGroup(
            jpMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpMainLayout.createSequentialGroup()
                .addComponent(jtbMain, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jMainSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 539, Short.MAX_VALUE))
        );

        jmbMenu.setName("jmbMenu"); // NOI18N

        jmFile.setMnemonic('f');
        jmFile.setText(resourceMap.getString("jmFile.text")); // NOI18N
        jmFile.setName("jmFile"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(net.ekology.EKology.class).getContext().getActionMap(EKologyView.class, this);
        jmiLoadModel.setAction(actionMap.get("loadModel")); // NOI18N
        jmiLoadModel.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.CTRL_MASK));
        jmiLoadModel.setMnemonic('m');
        jmiLoadModel.setActionCommand(resourceMap.getString("jmiLoadModel.actionCommand")); // NOI18N
        jmiLoadModel.setLabel(resourceMap.getString("jmiLoadModel.label")); // NOI18N
        jmiLoadModel.setName("jmiLoadModel"); // NOI18N
        jmFile.add(jmiLoadModel);
        jmiLoadModel.getAccessibleContext().setAccessibleName(resourceMap.getString("jmiLoadModel.AccessibleContext.accessibleName")); // NOI18N
        jmiLoadModel.getAccessibleContext().setAccessibleDescription(resourceMap.getString("jmiLoadModel.AccessibleContext.accessibleDescription")); // NOI18N

        jmiSaveProject.setAction(actionMap.get("saveProject")); // NOI18N
        jmiSaveProject.setMnemonic('s');
        jmiSaveProject.setName("jmiSaveProject"); // NOI18N
        jmFile.add(jmiSaveProject);

        jmiLoadProject.setAction(actionMap.get("loadProject")); // NOI18N
        jmiLoadProject.setMnemonic('l');
        jmiLoadProject.setName("jmiLoadProject"); // NOI18N
        jmFile.add(jmiLoadProject);

        jmiExit.setAction(actionMap.get("quit")); // NOI18N
        jmiExit.setMnemonic('x');
        jmiExit.setName("jmiExit"); // NOI18N
        jmFile.add(jmiExit);

        jmbMenu.add(jmFile);

        jmProject.setMnemonic('p');
        jmProject.setText(resourceMap.getString("jmProject.text")); // NOI18N
        jmProject.setEnabled(false);
        jmProject.setName("jmProject"); // NOI18N

        jMenuItem3.setAction(actionMap.get("showSignalMonitorDialog")); // NOI18N
        jMenuItem3.setMnemonic('m');
        jMenuItem3.setName("jmiSignalMonitor"); // NOI18N
        jmProject.add(jMenuItem3);

        jmbMenu.add(jmProject);

        jmHelp.setMnemonic('h');
        jmHelp.setText(resourceMap.getString("jmHelp.text")); // NOI18N
        jmHelp.setName("jmHelp"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        jmHelp.add(aboutMenuItem);

        jmbMenu.add(jmHelp);

        jpStatus.setBorder(null);
        jpStatus.setName("jpStatus"); // NOI18N

        statusPanelSeparator.setBorder(null);
        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout jpStatusLayout = new javax.swing.GroupLayout(jpStatus);
        jpStatus.setLayout(jpStatusLayout);
        jpStatusLayout.setHorizontalGroup(
            jpStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
            .addGroup(jpStatusLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 596, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        jpStatusLayout.setVerticalGroup(
            jpStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpStatusLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jpStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(jpMain);
        setMenuBar(jmbMenu);
        setStatusBar(jpStatus);
    }// </editor-fold>//GEN-END:initComponents
    private void oTreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_oTreeMouseClicked
        DefaultMutableTreeNode oSelectedNode;
        Argument oArgument;
        Object oValue;

        if (evt.getButton() == MouseEvent.BUTTON1) {
            this.oObjectPaneFactory.updatePane();
        }
}//GEN-LAST:event_oTreeMouseClicked

    private void oViewportPanelComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_oViewportPanelComponentResized
        oViewport.resize();
}//GEN-LAST:event_oViewportPanelComponentResized

    private void oViewportPanelMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_oViewportPanelMouseDragged
        double dXDisp, dYDisp;
        double dFactor = 1.0;
        EKVector oAgentPosition;
        EKVector oDispVector;
        Agent oAgent;
        
        
        dXDisp = -(this.oPoint.getX()-evt.getX());
        dYDisp = this.oPoint.getY()-evt.getY();
        oPoint = evt.getPoint();
        
        if ((evt.getModifiers() & MouseEvent.BUTTON3_MASK) == MouseEvent.BUTTON3_MASK) { // right mouse button moves the viewport
            oViewportPanel.setCursor(oViewportMoveCursor);
            
            if ((evt.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK ) dFactor /= 4;
            if ((evt.getModifiers() & MouseEvent.SHIFT_MASK) == MouseEvent.SHIFT_MASK ) dFactor *= 5;
            
            this.oViewport.translate(dXDisp*dFactor, dYDisp*dFactor);
        } else if ((evt.getModifiers() & MouseEvent.BUTTON2_MASK) == MouseEvent.BUTTON2_MASK) { // middle mouse button rotates the viewport
            oViewportPanel.setCursor(oViewportRotateCursor);
            
            if ((evt.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK ) dFactor /= 4;
            if ((evt.getModifiers() & MouseEvent.SHIFT_MASK) == MouseEvent.SHIFT_MASK ) dFactor *= 5;
            
            this.oViewport.rotate(dXDisp*dFactor);
        } else if ((evt.getModifiers() & MouseEvent.BUTTON1_MASK ) == MouseEvent.BUTTON1_MASK) { // left mouse button drags an agent
            oDispVector = new EKVector(dXDisp,dYDisp);

            oDispVector = this.oViewport.vectorTransoform(oDispVector);
            
            oAgent = oEKTree.getSelectedAgent();
            oAgentPosition = oAgent.getPosition();
            oAgentPosition.add(oDispVector);
            oAgent.setPosition(oAgentPosition);
            
            this.oViewport.repaint();
        }
}//GEN-LAST:event_oViewportPanelMouseDragged

    private void oViewportPanelMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_oViewportPanelMousePressed
        Point oPosPoint;
        
        this.oPoint = evt.getPoint();
        
        if (evt.getButton() == MouseEvent.BUTTON1) {
            oPosPoint = evt.getPoint();
            try {
                this.oViewport.getTransform().inverseTransform(oPosPoint, oPosPoint);
            } catch(Exception ignore){}
            oEKTree.selectAgent(oFecade.getNearestAgent(new EKVector(oPosPoint.getX(),oPosPoint.getY())));
        }
}//GEN-LAST:event_oViewportPanelMousePressed

    private void oViewportPanelMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_oViewportPanelMouseReleased
        oViewportPanel.setCursor(oViewportCursor);
}//GEN-LAST:event_oViewportPanelMouseReleased

    private void oViewportPanelMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_oViewportPanelMouseWheelMoved
        double dFactor = 0.2;
        
        if ((evt.getModifiers() & MouseEvent.CTRL_MASK) == MouseEvent.CTRL_MASK ) dFactor /= 4;
        if ((evt.getModifiers() & MouseEvent.SHIFT_MASK) == MouseEvent.SHIFT_MASK ) dFactor *= 5;
        
        oViewport.zoom(-evt.getWheelRotation()*dFactor);
}//GEN-LAST:event_oViewportPanelMouseWheelMoved

    private void oViewportPanelAncestorResized(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_oViewportPanelAncestorResized
        this.oViewport.resize();
}//GEN-LAST:event_oViewportPanelAncestorResized

    private void jResetViewportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jResetViewportButtonActionPerformed
        this.oViewport.reset();
    }//GEN-LAST:event_jResetViewportButtonActionPerformed

    private void jtbPlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtbPlayActionPerformed
        if (this.jtbPlay.isSelected()) oFecade.runSimulation();
        else {
            oFecade.stopSimulation();
            oEKTree.updateAgents(oFecade.getAgents());
            oObjectPaneFactory.updatePane();
        }
    }//GEN-LAST:event_jtbPlayActionPerformed

    private void jStepSimulationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jStepSimulationButtonActionPerformed
        oFecade.stepSimulation();
        oEKTree.updateAgents(oFecade.getAgents());
}//GEN-LAST:event_jStepSimulationButtonActionPerformed

    private void drawingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_drawingButtonActionPerformed
        oFecade.setDrawing(drawingButton.isSelected());
    }//GEN-LAST:event_drawingButtonActionPerformed

    private void timeFactorSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_timeFactorSpinnerStateChanged
        oFecade.setTimeFactor((Double) timeFactorSpinner.getValue());
    }//GEN-LAST:event_timeFactorSpinnerStateChanged

    private void oTreePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_oTreePropertyChange
        if (evt.getPropertyName().equals("leadSelectionPath")) oObjectPaneFactory.updatePane();
    }//GEN-LAST:event_oTreePropertyChange

    
    public DefaultMutableTreeNode getSelectedNode() {
        return (DefaultMutableTreeNode) oTree.getLastSelectedPathComponent();
    }
    
    
    public void repaintViewport() {
        oViewport.repaint();
    }
    
    
    public void addAgent(Agent oAgent) {
        BioticAgent oBioticAgent;
        AbioticAgent oAbioticAgent;
        Automaton oAutomaton;
        Genome oGenome;
        
        
        oGenome = oEKModel.getModelGenome(oAgent.getSpeciesName());
        
        if (oGenome != null) {
            if (oAgent.isBiotic()) {
                oBioticAgent = (BioticAgent) oAgent;
                oBioticAgent.setGenome(oGenome);
            }
            else {
                oAbioticAgent = (AbioticAgent) oAgent;
                oAutomaton = oGenome.getAutomaton();
                if (oAutomaton != null) oAbioticAgent.setAutomaton(oAutomaton);
            }
        }
        
        oFecade.addAgent(oAgent);
        oEKTree.addAgent(oAgent);
        repaintViewport();
    }
    
    
    public void removeAgent(Agent oAgent) {
        oEKTree.removeAgent(oAgent);
        oFecade.removeAgent(oAgent);
        repaintViewport();
    }
    
    
    public void setEKologyModel(Vector<Object> vModel) {
        oEKModel = new EKosystemModel(vModel);
        oEKTree.loadModel(oEKModel);
    }
    
    @Action
    public void loadProject() {
        File oFile;
        ObjectInputStream oisInput;

        oFile = showOpenFileDialog();

        if (oFile != null) {
            try {
                oisInput = new ObjectInputStream(new FileInputStream(oFile));
                
                oEKModel = (EKosystemModel) oisInput.readObject();
                
                oFecade.loadProject(oisInput);
                
                oEKTree.loadModel(oEKModel);
                oEKTree.updateAgents(oFecade.getAgents());

                oProject = new Project(oFile);
            
                jtbPlay.setEnabled(true);
                jStepSimulationButton.setEnabled(true);
                jmiSaveProject.getAction().setEnabled(true);
                jmProject.setEnabled(true);
                
                oViewport.updateUI();
                oEKTree.updateUI();
                
                oisInput.close();
                statusMessageLabel.setText("Project loaded.");
            } catch(Exception e) {
                e.printStackTrace();
                statusMessageLabel.setText("Error loading project.");
            }
        }
    }

    @Action
    public void saveProject() {
        File oFile;
        ObjectOutputStream oosOutput;

        oFile = showSaveFileDialog();

        if (oFile != null) {
            try {
                oosOutput = new ObjectOutputStream(new FileOutputStream(oFile));
                
                oosOutput.writeObject(oEKModel);
                
                oFecade.saveProject(oosOutput);

                oProject = new Project(oFile);
                oFecade.setProjectData(new ProjectData(oProject.getName(),(jdSignalMonitor==null)?"":jdSignalMonitor.getProjectNotes()));
                jmProject.setEnabled(true);
                
                oosOutput.close();
                statusMessageLabel.setText("Project saved.");
            } catch(Exception e) {
                e.printStackTrace();
                statusMessageLabel.setText("Error saving project.");
            }               
        }
    }
    

    @Action
    public void showSignalMonitorDialog() {
        if (jdSignalMonitor == null) {
            jdSignalMonitor = new SignalMonitorDialog(this);
            jdSignalMonitor.setLocationRelativeTo(jfMainFrame);
            
            restoreSignalMonitorDialog();
        }
        
        EKology.getApplication().show(jdSignalMonitor);
    }
    
    public void signalMonitorUpdated() {
        Vector vData,vRow;
        Signal[] aSignal;
        String sName;
        SignalType oType;
        long lInterval;
        SignalStatusType oStatus;
        
        oFecade.setProjectData(new ProjectData(oProject.getName(),jdSignalMonitor.getProjectNotes()));
        oFecade.setSessionData(new SessionData(jdSignalMonitor.getSessionName(),jdSignalMonitor.getSessionNotes()));
        oFecade.setMonitoring(jdSignalMonitor.getEnableMonitoring());
        
        vData = jdSignalMonitor.getDataVector();
        aSignal = new Signal[vData.size()];
        
        for(int i=0; i<vData.size(); i++) {
            vRow = (Vector) vData.get(i);
            
            sName = (String) vRow.get(0);
            oType =  SignalType.valueOf((String) vRow.get(1));
            lInterval = (Long) vRow.get(2);
            oStatus = SignalStatusType.valueOf((String) vRow.get(3));
            
            aSignal[i] = new Signal(sName,oType,lInterval,oStatus);
        }
        
        oFecade.setSignals(aSignal);
    }
    
    public void restoreSignalMonitorDialog() {
        Vector vData,vRow;
        ProjectData oProjectData;
        SessionData oSessionData;
        
        oProjectData = oFecade.getProjectData();
        if (oProjectData != null) {
            jdSignalMonitor.setProjectName(oProjectData.sName);
            jdSignalMonitor.setProjectNotes(oProjectData.sNotes);
        }
        else {
            jdSignalMonitor.setProjectName(oProject.getName());
            jdSignalMonitor.setProjectNotes("");
        }
        
        oSessionData = oFecade.getSessionData();
        if (oSessionData != null) {
            jdSignalMonitor.setSessionName(oSessionData.sName);
            jdSignalMonitor.setSessionNotes(oSessionData.sNotes);
        }
        else {
            jdSignalMonitor.setSessionName("");
            jdSignalMonitor.setSessionNotes("");
        }
        
        jdSignalMonitor.setEnableMonitoring(oFecade.getMonitoring());
        
        vData = new Vector();
        for(Signal oSignal: oFecade.getSignals()) {
            vRow = new Vector(Arrays.asList(oSignal.getName(),oSignal.getType().toString(),oSignal.getInterval(),oSignal.getStatus().toString()));
            vData.add(vRow);
        }
        jdSignalMonitor.setDataVector(vData);
    }
    
    public void reset() {
        oEKModel = null;
        oProject = null;
        oViewport.reset();
        oEKTree.reset();
        
        
        jtbPlay.setEnabled(false);
        jStepSimulationButton.setEnabled(false);
        jmProject.setEnabled(false);
        jmiSaveProject.getAction().setEnabled(false);
        
        oObjectPaneFactory.updatePane();
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton drawingButton;
    private javax.swing.JSplitPane jMainSplitPane;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JButton jResetViewportButton;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JSplitPane jSplitControlPane;
    private javax.swing.JButton jStepSimulationButton;
    private javax.swing.JMenu jmProject;
    private javax.swing.JMenuBar jmbMenu;
    private javax.swing.JMenuItem jmiLoadModel;
    private javax.swing.JMenuItem jmiLoadProject;
    private javax.swing.JMenuItem jmiSaveProject;
    private javax.swing.JPanel jpMain;
    private javax.swing.JPanel jpStatus;
    private javax.swing.JScrollPane jspEKosystemTree;
    private javax.swing.JScrollPane jspObjectPane;
    private javax.swing.JToolBar jtbMain;
    private javax.swing.JToggleButton jtbPlay;
    private javax.swing.JTree oTree;
    private javax.swing.JPanel oViewportPanel;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JLabel timeFactorLabel;
    private javax.swing.JSpinner timeFactorSpinner;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JFrame jfMainFrame = EKology.getApplication().getMainFrame();
    private JDialog jdAboutBox;
    private SignalMonitorDialog jdSignalMonitor;
    private JFileChooser jfcDirectoryChooser = new JFileChooser();
    private JFileChooser jfcFileChooser = new JFileChooser();
    private ObjectPaneFactory oObjectPaneFactory;
    private Fecade oFecade;
    private EKologyViewport oViewport;
    private EKosystemTree oEKTree;
    private Point oPoint = null;
    private Project oProject;
    
    private Cursor oViewportCursor = new Cursor(Cursor.CROSSHAIR_CURSOR);
    private Cursor oViewportMoveCursor = new Cursor(Cursor.HAND_CURSOR);
    private Cursor oViewportRotateCursor = new Cursor(Cursor.NE_RESIZE_CURSOR);
    
    private EKosystemModel oEKModel;
    
}

